package v2.parser.tree

import v2.parser.Link

/**
 * @author bweber
 * @version $Rev$, $Date$
 */

class Navigation  protected (var currentTree: TypedTree) {

  def ls() = {
    var children = List[String]()
    currentTree.listChildren.foreach {
      c =>
              children = c :: children
    }
    children
  }

  def absolute_cd(names: String*):TypedTree = {
    root_cd()
    val arr: Seq[String] = names.toSeq
    if (currentTree.name != arr.first) {
      throw new RuntimeException("Invalid root name: " + arr.first)
    }
    relative_cd(arr.subseq(1, arr.length + 1): _*)
  }

  def relative_cd(names: String*):TypedTree = {
    names.foreach {
      name =>
              // handle soft links
              if ( currentTree.getChild(name).isInstanceOf[Link] ) {
                currentTree = absolute_cd(currentTree.getChild(name).asInstanceOf[Link].pointsAt:_*)
              }
              else {
                currentTree = new TypedTree(currentTree, name, currentTree.getChild(name))
              }
    }
    currentTree
  }

  def root_cd() = {
    while (currentTree.parentNode != null) {
      currentTree = currentTree.parentNode
    }
  }

  def up_cd() = {
    currentTree = currentTree.parentNode
  }

  def pwd(): List[String] = {
    var path = List[String](currentTree.name)
    var parent = currentTree.parentNode
    while (parent != null) {
      path = parent.name :: path
      parent = parent.parentNode
    }
    path
  }

  def current_type() = {
    currentTree.currentNode.getType.name
  }
}

object Navigation {
  def apply(typedTree: TypedTree) = {
    new Navigation(typedTree)
  }
}